package com.fg.pro.trade.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fg.pro.model.trade.dto.GmOrderDto;
import com.fg.pro.trade.dao.TradeOrderDao;
import com.fg.pro.trade.entity.TradeGoods;
import com.fg.pro.trade.entity.TradeGoodsUnit;
import com.fg.pro.trade.entity.TradeOrder;
import com.fg.pro.trade.entity.TradeOrderDetail;
import com.fg.pro.trade.service.TradeOrderDetailService;
import com.fg.pro.trade.service.TradeOrderService;
import com.fg.pro.trade.utils.GmHttpUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

import static com.fg.pro.trade.utils.GmRequestUrl.*;

/**
 * 订单(TradeOrder)表服务实现类
 *
 * @author makejava
 * @since 2025-08-17 10:01:50
 */
@Service("tradeOrderService")
public class TradeOrderServiceImpl extends ServiceImpl<TradeOrderDao, TradeOrder> implements TradeOrderService {
    @Autowired
    GmHttpUtils gmHttpUtils;
    @Autowired
    RedissonClient redissonClient;
    @Resource
    private TradeOrderDetailService tradeOrderDetailService;
    @Override
    public boolean refresh(Date start, Date end) {
//        RLock lock = redissonClient.getLock(REDIS_LOCK_URL+GM_CATEGORY_URL);
//        boolean tryLock = lock.tryLock();
//        if(!tryLock){
//            return false;
//        }
//        try {
//            return refreshTradeOrderByLock(start,end);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        } finally {
//            lock.unlock();
//        }

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    refreshTradeOrderByLock(start,end);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "refreshTradeOrderByLock");
        thread.start();
        return false;
    }


    @Override
    public PageInfo getPage(Integer pageNum, Integer pageSize, Date start, Date end, String orderCode, String selectType) {
        SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PageHelper.startPage(pageNum, pageSize);
        List<TradeOrder> list = query()
                .ge("order_receive_time",sdfs.format(DateUtil.beginOfDay(start)))
                .le("order_receive_time",sdfs.format(DateUtil.endOfDay(end)))
                .eq(StrUtil.isNotBlank(selectType),"order_state", selectType)
                .like(StrUtil.isNotBlank(orderCode),"order_serial_no",orderCode)
                .orderByDesc("order_receive_time")
                .list();
        PageInfo<TradeOrder> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Transactional
    public boolean refreshTradeOrderByLock(Date start, Date end) throws InterruptedException {
        if(start == null || end == null){
            start=new Date();
            end=new Date();
        }
        DateTime beginOfDay = DateUtil.beginOfDay(start);
        DateTime endOfDay = DateUtil.endOfDay(end);
        LinkedList<TradeOrder> newList = new LinkedList<>();
        LinkedList<TradeOrderDetail> detailList = new LinkedList<>();
// 获取请求参数 条件变量
        int num = 0;
        int limit = 50;
        while (true) {
            System.out.println("num-->" + num);
            System.out.println("offset-->" + num * limit);
            GmOrderDto.GmOrderReponse gmOrderReponse = gmHttpUtils.httpPostByToken(GM_ORDER_URL, new GmOrderDto().new GmOrderRequest(beginOfDay, endOfDay, limit, num * limit), GmOrderDto.GmOrderReponse.class);
            for (GmOrderDto.GmOrderReponse.GmOrderData gmOrderData : gmOrderReponse.getOrders()) {
                TradeOrder tradeOrder = new TradeOrder();
                tradeOrder.setId(gmOrderData.getOrder_id());
                System.out.println("訂單id------------------------------------------------------------------------------------------------------------------------" + tradeOrder.getId());
                tradeOrder.setCreateTime(new Date(gmOrderData.getCreate_time()));
                tradeOrder.setUpdateTime(new Date(gmOrderData.getUpdate_time()));
                tradeOrder.setOrderUseTime(new Date(gmOrderData.getUse_time()));
                tradeOrder.setOrderReceiveTime(new Date(gmOrderData.getReceive_time()));
                tradeOrder.setOrderOutstockTime(gmOrderData.getOutstock_time() == null ? null : new Date(gmOrderData.getOutstock_time()));
                tradeOrder.setOrderTime(new Date(gmOrderData.getOrder_time()));
                tradeOrder.setOrderStatus(gmOrderData.getStatus());
                tradeOrder.setOrderRevision(gmOrderData.getRevision());
                tradeOrder.setOrderGroupId(gmOrderData.getGroup_id());
                tradeOrder.setOrderStationId(gmOrderData.getStation_id());
                tradeOrder.setOrderCreatorId(gmOrderData.getCreator_id());
                tradeOrder.setOrderBillCustomerId(gmOrderData.getBill_customer_id());
                tradeOrder.setOrderDriverId(gmOrderData.getDriver_id());
                tradeOrder.setOrderReceiveCustomerId(gmOrderData.getReceive_customer_id());
                tradeOrder.setOrderQuotationId(gmOrderData.getQuotation_id());
                tradeOrder.setOrderCustomerType(gmOrderData.getCustomer_type());
                tradeOrder.setOrderServicePeriodId(gmOrderData.getService_period_id());
                tradeOrder.setOrderPrice(gmOrderData.getOrder_price());
                tradeOrder.setOrderAftersalePrice(gmOrderData.getAftersale_price());
                tradeOrder.setOrderOutstockPrice(gmOrderData.getOutstock_price());
                tradeOrder.setOrderSalePrice(gmOrderData.getSale_price());
                tradeOrder.setOrderSalePriceNoTax(gmOrderData.getSale_price_no_tax());
                tradeOrder.setOrderSalePriceNoAftersale(gmOrderData.getSale_price_no_aftersale());
                tradeOrder.setOrderDetailSumSalePrice(gmOrderData.getDetail_sum_sale_price());
                tradeOrder.setOrderDetailSumSalePriceNoTax(gmOrderData.getDetail_sum_sale_price_no_tax());
                tradeOrder.setOrderDetailSumTaxPrice(gmOrderData.getDetail_sum_tax_price());
                tradeOrder.setOrderTotalAddOrderPrice(gmOrderData.getTotal_add_order_price());
//            tradeOrder.setOrderAddSumOrderPrice(gmOrderData.getTotal_add_order_price());
                tradeOrder.setOrderFakeOrderPrice(gmOrderData.getFake_order_price());
                tradeOrder.setOrderFakeOutstockPrice(gmOrderData.getFake_outstock_price());
                tradeOrder.setOrderFakePrintPrice(gmOrderData.getFake_print_price());
                tradeOrder.setOrderSerialNo(gmOrderData.getSerial_no());
                tradeOrder.setOrderState(gmOrderData.getState());
                tradeOrder.setOrderPayState(gmOrderData.getPay_state());
                tradeOrder.setOrderType(gmOrderData.getOrder_type());
                tradeOrder.setOrderCreatorIdType(gmOrderData.getCreator_id_type());
                tradeOrder.setOrderRemark(gmOrderData.getRemark());
                tradeOrder.setOrderAppType(gmOrderData.getApp_type());
                tradeOrder.setOrderIsRealOrder(gmOrderData.getIs_real_order());
                tradeOrder.setOrderSortingTotalCount(gmOrderData.getSorting_info().getTotal_count());
                tradeOrder.setOrderSortingUnweightCount(gmOrderData.getSorting_info().getUnweight_count());
                tradeOrder.setOrderSortingOutStockCount(gmOrderData.getSorting_info().getOut_stock_count());
                tradeOrder.setOrderOp(gmOrderData.getOrder_op());
                tradeOrder.setOrderUpdaterIdType(gmOrderData.getUpdater_id_type());
                tradeOrder.setOrderCustomerFirId(gmOrderData.getCustomer_id_l1());
                tradeOrder.setOrderCustomerSecId(gmOrderData.getCustomer_id_l2());
                tradeOrder.setOrderSupplierCooperateModelType(gmOrderData.getSupplier_cooperate_model_type());
                tradeOrder.setOrderDetailLength(gmOrderData.getDetail_length());
                tradeOrder.setOrderRawDetailLength(gmOrderData.getRaw_detail_length());
                tradeOrder.setOrderOutstockState(gmOrderData.getOutstock_state());
                tradeOrder.setOrderOutstockState(gmOrderData.getLock_state());
                tradeOrder.setOrderTotalAddOrderValueQuantity(gmOrderData.getTotal_add_order_value_quantity());
                tradeOrder.setOrderExtraOrderPrice(gmOrderData.getExtra_order_price());
                tradeOrder.setOrderReceiveCustomerName(gmOrderData.getReceive_customer_name());
                tradeOrder.setOrderCost(gmOrderData.getCost());
                newList.add(tradeOrder);
                for (GmOrderDto.GmOrderReponse.GmOrderData.OrderDetails.OrderDetailsData gmOrderDetail : gmOrderData.getOrder_details().getOrder_details()) {
                    TradeOrderDetail tradeOrderDetail = new TradeOrderDetail();
                    tradeOrderDetail.setReceiveTime(new Date(gmOrderData.getReceive_time()));
                    tradeOrderDetail.setId(gmOrderDetail.getOrder_detail_id());
                    tradeOrderDetail.setCreateTime(new Date(gmOrderDetail.getCreate_time()));
                    tradeOrderDetail.setUpdateTime(new Date(gmOrderDetail.getUpdate_time()));
                    tradeOrderDetail.setOrderId(gmOrderDetail.getOrder_id());
                    tradeOrderDetail.setOrderDetailType(gmOrderDetail.getType());
                    tradeOrderDetail.setOrderDetailGroupId(gmOrderDetail.getGroup_id());
                    tradeOrderDetail.setOrderDetailStationId(gmOrderDetail.getStation_id());
                    tradeOrderDetail.setSkuId(gmOrderDetail.getSku_id());
                    tradeOrderDetail.setOrderDetailDetailRandomId(gmOrderDetail.getDetail_random_id());
                    tradeOrderDetail.setOrderDetailTotalAddOrderPrice(gmOrderDetail.getTotal_add_order_price());
                    tradeOrderDetail.setOrderDetailFakeOrderPrice(gmOrderDetail.getFake_order_price());
                    tradeOrderDetail.setOrderDetailOutstockPrice(gmOrderDetail.getOutstock_price());
                    tradeOrderDetail.setOrderDetailIsPrint(gmOrderDetail.getIs_print());
                    tradeOrderDetail.setOrderDetailFakeType(gmOrderDetail.getFake_type());
                    tradeOrderDetail.setOrderDetailOrderPrice(gmOrderDetail.getOrder_price());
                    tradeOrderDetail.setOrderDetailOutstockPrice(gmOrderDetail.getOutstock_cost_price());
                    tradeOrderDetail.setOrderDetailSalePrice(gmOrderDetail.getSale_price());
                    tradeOrderDetail.setSalePriceNoTax(gmOrderDetail.getSale_price_no_tax());
                    tradeOrderDetail.setOrderDetailTaxPrice(gmOrderDetail.getTax_price());
                    tradeOrderDetail.setOrderDetailOutstockCostPrice(gmOrderDetail.getOutstock_cost_price());
                    tradeOrderDetail.setOrderDetailSortingStatus(gmOrderDetail.getSorting_status());
                    tradeOrderDetail.setOrderDetailSupplierCooperateModelType(gmOrderDetail.getSupplier_cooperate_model_type());
                    tradeOrderDetail.setOrderDetailUnitId(gmOrderDetail.getUnit_id());
                    tradeOrderDetail.setOrderDetailSkuRevision(gmOrderDetail.getSku_revision());
                    tradeOrderDetail.setOrderDetailFeeUnitId(gmOrderDetail.getFee_unit_id());
                    tradeOrderDetail.setOrderDetailSkuName(gmOrderDetail.getSku_name());
                    tradeOrderDetail.setOrderDetailSkuCustomizeCode(gmOrderDetail.getSku_customize_code());
                    tradeOrderDetail.setOrderDetailReceiveCustomerId(gmOrderDetail.getReceive_customer_id());
                    tradeOrderDetail.setOrderDetailCost(gmOrderDetail.getCost());
                    tradeOrderDetail.setOrderDetailFeePrice(gmOrderDetail.getFee_price());
                    tradeOrderDetail.setOrderDetailIsNeedTakeOut(gmOrderDetail.getIs_need_take_out());
                    tradeOrderDetail.setOrderDetailReceiveCustomerName(gmOrderDetail.getReceive_customer_name());
                    tradeOrderDetail.setOrderDetailSupplierId(gmOrderDetail.getSupplier_id());
                    tradeOrderDetail.setOrderDetailCategoryFirId(gmOrderDetail.getCategory1_id());
                    tradeOrderDetail.setOrderDetailCategorySecId(gmOrderDetail.getCategory2_id());
                    tradeOrderDetail.setOrderDetailCategoryFirName(gmOrderDetail.getCategory1_name());
                    tradeOrderDetail.setOrderDetailCategorySecName(gmOrderDetail.getCategory2_name());
                    tradeOrderDetail.setOrderDetailOutstockState(gmOrderDetail.getOutstock_state());
                    tradeOrderDetail.setOrderDetailSerialNo(gmOrderDetail.getSerial_no());
                    tradeOrderDetail.setOrderDetailOutstockUnitQuantity(gmOrderDetail.getOrder_unit_quantity());
                    tradeOrderDetail.setOrderDetailOutstockUnitId(gmOrderDetail.getOutstock_unit_id());
                    tradeOrderDetail.setOrderDetailOutstockBaseUnitQuantity(gmOrderDetail.getOutstock_base_unit_quantity());
                    tradeOrderDetail.setOrderDetailOutstockBaseUnitId(gmOrderDetail.getOutstock_base_unit_id());
                    tradeOrderDetail.setOrderDetailAcceptValueQuantity(gmOrderDetail.getAccept_value_quantity());
                    tradeOrderDetail.setOrderDetailOriginalPrice(gmOrderDetail.getOriginal_price());
                    tradeOrderDetail.setOrderDetailOriginalUnitId(gmOrderDetail.getOriginal_unit_id());
                    tradeOrderDetail.setOrderDetailOriginalRate(gmOrderDetail.getOriginal_rate());
                    tradeOrderDetail.setOrderUnitQuantity(gmOrderDetail.getOrder_unit_quantity());
                    // 观麦接口 报错
//                        tradeOrderDetail.setOrderDetailTax(gmOrderDetail.getTax());
                    detailList.add(tradeOrderDetail);
                }
            }
            if (!gmOrderReponse.getPaging().has_more) {
                break;
            }
            num+=1;
            TimeUnit.SECONDS.sleep(2);

        }
        boolean save = saveOrUpdateBatch(newList);
        boolean saveOrUpdateBatch = tradeOrderDetailService.saveOrUpdateBatch(detailList);
        return save;
    }


}

